<template>
  <div class="app-container">
    <div class="flex mb-4">
      <div class="md:w-1/3">
        <p class="text-xl mb-2">总计</p>
        <el-table :data="totalData" border stripe>
          <el-table-column v-for="col in columns"
            :prop="col.property"
            :key="col.id"
            :label="col.label"
            :width="col.width">
          </el-table-column>
        </el-table>
      </div>
      <div class="flex-grow ml-8">
        <p class="text-xl mb-2">筛选</p>
        <div class="flex">
          
          <div>
            <span>渠道名称：</span>
            <el-input
              class="marginRB10"
              v-model="listQuery.name"
              placeholder="请输入渠道名称"
              style="width: 200px"
              clearable
            ></el-input>
          </div>
          <div>
            <span>状态：</span>
            <el-select filterable
              v-model="listQuery.state"
              class="filter-item marginRB10"
              placeholder="请选择状态"
              style="width: 200px"
            >
              <el-option
                v-for="item in selectList2"
                :key="item.key"
                :label="item.lab"
                :value="item.key"
              ></el-option>
            </el-select>
          </div>
          <div>
            <span>渠道编号：</span>
            <el-input
              class="marginRB10"
              v-model="listQuery.channel_no"
              placeholder="请输入渠道编号"
              style="width: 200px"
              clearable
            ></el-input>
          </div>
          <el-button
            type="primary"
            @click="getList"
            icon="el-icon-search"
            class="marginRB10">搜索</el-button>
            <el-button class="marginRB10" @click="resetSubmit">重置</el-button>
        </div>
      </div>
    </div>
    <div class="flex items-center justify-between">
      <p class="text-xl">渠道列表（{{total}}）</p>
      <el-button
        class="filter-item marginRB10"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate()"
        >添加</el-button
      >
    </div>
    

    <el-table
      ref="dataList"
      :data="menuList"
      style="margin-bottom: 20px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="channel_no" label="渠道编号"></el-table-column>
      <el-table-column prop="name" label="渠道名称"></el-table-column>
      <el-table-column prop="id" label="渠道ID"></el-table-column>
      <el-table-column prop="user_total" label="邀请人数（人）" sortable width="150"></el-table-column>
      <el-table-column prop="recharge_total" label="充值金额（元）" sortable width="150"></el-table-column>
      <el-table-column prop="add_time" label="创建时间" sortable></el-table-column>
      <!-- <el-table-column prop="register_link" label="注册链接"></el-table-column>
      <el-table-column prop="channel_user_link" label="渠道用户链接"></el-table-column> -->
      <el-table-column prop="room_code" label="房间ID"></el-table-column>
      <!-- <el-table-column prop="remark" label="备注"> </el-table-column> -->
      <el-table-column prop="state" label="状态">
        <template slot-scope="scope">
          {{ scope.row.state === 1 ? "开启" : "" }}
          {{ scope.row.state === 2 ? "关闭" : "" }}
        </template>
      </el-table-column>
      <el-table-column min-width="180" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleCheck(scope.row)"
            plain
          >查看</el-button>
          <!-- <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            plain
          >编辑</el-button> -->
          <el-button
            type="primary"
            size="mini"
            @click="handleCopy(scope.row)"
            plain
          >复制链接</el-button>
          <!-- <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />

    <!-- 复制弹窗 -->
    <el-dialog
      title="是否复制"
      :visible.sync="dialogCopyVisible"
      width="30%"
      @close="closeCopyDialog">
      <div class="flex">
        <span>渠道链接：</span>
        <p>{{channel_user_link}}</p>
      </div>
      <div class="flex">
        <span>注册链接：</span>
        <p>{{register_link}}</p>
      </div>
      <span slot="footer">
        <el-button @click="dialogCopyVisible = false">取消</el-button>
        <el-button type="primary" @click="copyContent">复制</el-button>
      </span>
    </el-dialog>
    

    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="渠道编号" prop="channel_no">
          <el-input v-model="form.channel_no" placeholder="请输入渠道编号" />
        </el-form-item>
        <el-form-item label="渠道名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="房间号" prop="room_code">
          <el-input v-model="form.room_code" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="渠道备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入渠道备注"
          />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select filterable
            v-model="form.state"
            class="filter-item marginRB10"
            placeholder="请选择状态"
            style="width: 280px"
          >
            <el-option
              v-for="item in selectList"
              :key="item.key"
              :label="item.lab"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveData,
  deleteData,
  updateData,
  listData,
} from "@/api/channel/channel";
export default {
  data() {
    return {
      dialogCopyVisible: false,
      channel_user_link: '',
      register_link: '',
      totalData: [],
      columns: [
        {
          id: 1,
          label: '渠道总邀请人数(人)',
          property: 'user_total',
          width: 'auto'
        },
        {
          id: 2,
          label: '总充值金额（元）',
          property: 'recharge_total',
          width: 'auto'
        },
      ],
      confirmBtn: false,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
      },
      selectList: [
        { key: 1, lab: "开启 " },
        { key: 2, lab: "关闭" },
      ],
      selectList2: [
        { key: undefined, lab: "全部状态" },
        { key: "1", lab: "开启 " },
        { key: "2", lab: "关闭" },
      ],
      menuList: [],
      dialogFormVisible: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加",
      },
      form: {
        id: undefined,
        name: undefined,
        channel_no: undefined,
        remark: undefined,
        state: undefined,
      },
      rules: {
        name: [{ required: true, message: "请输入渠道名称", trigger: "blur" }],
        channel_no: [
          { required: true, message: "请输入渠道编号", trigger: "blur" },
        ],
        state: [{ required: true, message: "请输入状态", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      for (let key in this.listQuery) {
        this.listQuery[key] = this.listQuery[key] === "" ? undefined : this.listQuery[key];
      }
      listData(this.listQuery).then(({data}) => {
        this.menuList = data.list
        this.total = data.meta.total
        this.listLoading = false
        this.confirmBtn = false
        this.totalData = [data.header]
      })
    },
    handleCreate(row) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.form = [];
      this.form.id = row.id;
      this.form.name = row.name;
      this.form.channel_no = row.channel_no;
      this.form.remark = row.remark;
      this.form.state = row.state;
      this.form.room_code = row.room_code;

      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      this.form = Object.assign({}, this.form);
    },
    handleCheck(row) {
      this.$router.push({
        path: 'channelUser',
        query: {
          channel_no: row.channel_no
        }
      })
    },
    handleDelete(row) {
      if (this.confirmBtn) return;
      this.confirmBtn = true;

      let data = { id: row.id };
      deleteData(data).then((response) => {
        if (response.code === 200) {
          this.getList();
          // this.submitOk('删除成功')
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000,
          });
        } else {
          this.confirmBtn = false;
        }
      });
    },
    allDel() {
      if (this.confirmBtn) return;
      this.confirmBtn = true;
      let delNum = [];
      this.$refs.dataList.selection.forEach((k) => {
        delNum.push(k.id);
      });
      if (delNum.length === 0) {
        return;
      }
      let data = { ids: delNum.toString() };
      deleteData(data).then((response) => {
        if (response.code === 200) {
          this.getList();
          // this.submitOk('删除成功')
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000,
          });
        } else {
          this.confirmBtn = false;
        }
      });
    },
    submitForm() {
      if (this.confirmBtn) return;
      this.$refs["dataForm"].validate((valid) => {
        if (valid && this.dialogStatus === "create") {
          this.confirmBtn = true;
          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined
              ? ""
              : formData.append(item, this.form[item]);
          }
          saveData(formData).then((response) => {
            if (response.code === 200) {
              this.getList();
              // this.submitOk(response.message)
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000,
              });
              this.dialogFormVisible = false;
            } else {
              this.confirmBtn = false;
            }
          });
        } else if (valid && this.dialogStatus === "update") {
          this.confirmBtn = true;
          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined
              ? ""
              : formData.append(item, this.form[item]);
          }
          updateData(formData).then((response) => {
            if (response.code === 200) {
              this.getList();
              // this.submitOk(response.message)
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000,
              });
              this.dialogFormVisible = false;
            } else {
              this.confirmBtn = false;
            }
          });
        }
      });
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: undefined,
        channel_no: undefined,
        remark: undefined,
        state: undefined,
      };
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    },
    resetSubmit() {
      this.listQuery= {
        page: 1,
        perPage: 10,
      }
    },
    handleCopy(item) {
      this.dialogCopyVisible = true
      this.channel_user_link = item.channel_user_link
      this.register_link = item.register_link
    },
    copyContent() {
      let link = '渠道链接：' + this.channel_user_link + '；注册链接：' + this.register_link
      let copyInput = document.createElement('input')
      document.body.appendChild(copyInput)
      copyInput.setAttribute('value',link)
      copyInput.select()
      document.execCommand('copy')
      this.$notify({
        type: "success",
        message: "操作成功",
        position: "top-right",
        showClose: false,
        duration: 3000,
      });
      copyInput.remove()
      this.dialogCopyVisible = false
    },
    closeCopyDialog() {
      this.channel_user_link = ''
      this.register_link = ''
    }
  },
};
</script>
